﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml.Serialization;

namespace 通用类库.Utils
{
    public class StringUtil
    {
        public static string ReplaceSpecificCharacter(string sourceString, string searchString, string replacedWith)
        {
            string strReturn = sourceString;
            strReturn = strReturn.Replace(searchString, replacedWith);
            return strReturn;
        }
        public static short? ConvertShort(string strValue)
        {
            short? returnValue = null;
            short innerValue = 0;
            if (short.TryParse(strValue, out innerValue))
                returnValue = innerValue;
            return returnValue;
        }

        public static string AsciiToString(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                throw new Exception("ASCII Code is not valid.");
            }
        }
        public static T ConvertToEnum<T>(string enumValue)
        {
            return (T)Enum.Parse(typeof(T), enumValue, true);
        }
        public static T ConvertToEnum<T>(short enumValue)
        {
            return (T)Enum.Parse(typeof(T), enumValue.ToString(), true);
        }
        public static string TrimUnPrintChar(byte[] bytes, Int32 index, Int32 length)
        {
            string strReturn = string.Empty;
            strReturn = Encoding.UTF8.GetString(bytes, index, length);
            strReturn = strReturn.Trim();
            strReturn = strReturn.ToLower().TrimEnd(new char[] { '\0' });
            return strReturn;
        }

        #region 反序列化
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T Deserialize<T>(Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(typeof(T));
            return (T)xmldes.Deserialize(stream);
        }
        #endregion

        #region 序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer<T>(T obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(typeof(T));
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

        #endregion



        /// <summary>
        /// Save the Input string to hashtable ,the key is the first ,the value is the second.
        /// </summary>
        /// <param name="lsInput">Input string </param>
        /// <param name="cSeparator">the first split char</param>
        /// <param name="cEqual">the second split char</param>
        /// <returns>the hashtable</returns>
        public static Hashtable tokenize(string lsInput, char cSeparator, char cEqual)
        {
            Hashtable lhtRet = new Hashtable();
            string[] laInput = lsInput.Split(cSeparator);

            int i;

            for (i = 0; i < laInput.Length; i++)
            {
                string[] laPara = laInput[i].Split(cEqual);

                if (laPara.Length > 1)
                {
                    lhtRet[laPara[0]] = laPara[1];
                }
            }
            return lhtRet;
        }
         

        public static string hash2StringNoEncode(Hashtable lhtInput)
        {
            string lsRet = "";

            foreach (string lsKey in lhtInput.Keys)
            {
                lsRet += lsKey + "=" + lhtInput[lsKey].ToString() + "&";
            }

            return lsRet;

        }
         


        //public static string arrayList2String(ArrayList lalInput)
        //{
        //    string lsRet = "";
        //    int i;



        //    foreach (string lsKey in lalInput)
        //    {
        //        lsRet += lsKey + "=" + System.Web.HttpUtility.UrlEncode(lalInput.i[lsKey].ToString()) + "&";
        //    }

        //    return lsRet;
        //}

        /// <summary>
        /// Gets the regular expression result.
        /// </summary>
        /// <param name="lsTmp">The input string.</param>
        /// <param name="lsParttern">The  parttern.</param>
        /// <returns>the strings that match the parttern.</returns>
        public static string getRegularExpressionResult(string lsTmp, string lsParttern)
        {
            string lsRet = "";

            Regex lRegEx = new Regex(lsParttern);
            Match m = lRegEx.Match(lsTmp);

            while (m.Success)
            {
                int i, j;
                for (i = 1; i <= 2; i++)
                {
                    Group g = m.Groups[i];
                    CaptureCollection cc = g.Captures;

                    for (j = 0; j < cc.Count; j++)
                    {
                        Capture c = cc[j];
                        lsRet = c.Value;
                    }
                }
                m = m.NextMatch();
            }

            return lsRet;
        }

        /// <summary>
        /// Gets the regular expression result form array list.
        /// </summary>
        /// <param name="lsTmp">The input string .</param>
        /// <param name="lsParttern">The  parttern.</param>
        /// <param name="lRegexOptions">The l regex options.</param>
        /// <returns>a allayList that match the parttern</returns>
        public static ArrayList getRegularExpressionResultForArrayList(string lsTmp, string lsParttern, RegexOptions lRegexOptions)
        {
            ArrayList lalRet = new ArrayList();
            Match m = Regex.Match(lsTmp, lsParttern, lRegexOptions);

            int i, j;
            Group g;
            Capture c;
            CaptureCollection cc;

            while (m.Success)
            {
                for (i = 1; i <= m.Groups.Count; i++)
                {
                    g = m.Groups[i];
                    cc = g.Captures;

                    for (j = 0; j < cc.Count; j++)
                    {
                        c = cc[j];
                        lalRet.Add(c.Value);
                    }
                }
                m = m.NextMatch();
            }

            return lalRet;
        }

        /// <summary>
        /// Gets the regular expression result for array list.
        /// </summary>
        /// <param name="lsTmp">The input string .</param>
        /// <param name="lsParttern">The  parttern.</param>
        /// <returns></returns>
        public static ArrayList getRegularExpressionResultForArrayList(string lsTmp, string lsParttern)
        {
            ArrayList lalRet = new ArrayList();

            Regex lRegEx = new Regex(lsParttern);

            Match m = lRegEx.Match(lsTmp);

            int i, j;
            Group g;
            Capture c;
            CaptureCollection cc;

            while (m.Success)
            {

                for (i = 1; i <= m.Groups.Count; i++)
                {
                    g = m.Groups[i];
                    cc = g.Captures;

                    for (j = 0; j < cc.Count; j++)
                    {
                        c = cc[j];
                        lalRet.Add(c.Value);
                    }
                }
                m = m.NextMatch();
            }
            return lalRet;
        }

        /// <summary>
        /// Trims the blacket.
        /// </summary>
        /// <param name="lsInput">The  input.</param>
        /// <returns></returns>
        public static string trimBlacket(string lsInput)
        {
            if (lsInput.Length > 0)
            {
                if (lsInput.StartsWith("("))
                {
                    if (lsInput.Length >= 2)
                    {
                        lsInput = lsInput.Substring(1, lsInput.Length - 1);
                    }
                    else
                    {
                        lsInput = "";
                    }
                }

                if (lsInput.EndsWith(")"))
                {
                    if (lsInput.Length >= 2)
                    {
                        lsInput = lsInput.Substring(0, lsInput.Length - 1);
                    }
                    else
                    {
                        lsInput = "";
                    }
                }
            }
            return lsInput;
        }

        /// <summary>
        /// Removes the HTML.
        /// </summary>
        /// <param name="lsInput">The  input.</param>
        /// <returns></returns>
        public static string removeHTML(string lsInput)
        {
            Regex lRegEx = new Regex("<[^>]*>", RegexOptions.IgnoreCase);
            return lRegEx.Replace(lsInput, " ");
        }

        /// <summary>
        /// Gets the string with trim.
        /// </summary>
        /// <param name="lObj">The object need deal with.</param>
        /// <returns></returns>
        public static string getStringWithTrim(object lObj)
        {
            string lsRet = "";
            try
            {
                lsRet = "" + lObj.ToString();
                lsRet = lsRet.Trim();
            }
            catch
            {
                lsRet = "";
            }
            return lsRet;
        }

        /// <summary>
        /// convert the input string to int ,if the input value isn't a int,return -1
        /// </summary>
        /// <param name="lsInput">The  input string of integer.</param>
        /// <returns></returns>
        public static int getInt(string lsInput)
        {
            int ldRet;
            if (int.TryParse(lsInput, out ldRet))
                return ldRet;
            else
                return -1;

            //int liRet;

            //try
            //{
            //    liRet = int.Parse(lsInput);
            //}
            //catch
            //{
            //    liRet = -1;
            //}

            //return liRet;
        }

        /// <summary>
        /// convert the input string to int ,if the input value isn't a decimal,return 0
        /// </summary>
        /// <param name="lsInput">The  input string of decimal.</param>
        /// <returns></returns>
        public static decimal getDecimal(string lsInput)
        {
            decimal ldRet;
            if (Decimal.TryParse(lsInput, out ldRet))
                return ldRet;
            else
                return 0;

            //try
            //{
            //    ldRet = decimal.Parse(lsInput);
            //}
            //catch
            //{
            //    ldRet = 0;
            //}

            //return ldRet;
        }

        /// <summary>
        /// Gets the text from file.
        /// </summary>
        /// <param name="lsFilePaths">The  file paths.</param>
        /// <returns></returns>
        public static string getTextFromFile(string lsFilePaths)
        {
            return File.ReadAllText(lsFilePaths);
            //string lsRet;
            //StreamReader re = File.OpenText(lsFilePaths);
            //lsRet = re.ReadToEnd();
            //re.Close();
            //return lsRet;
        }

        /// <summary>
        /// Removes the \r and \n
        /// </summary>
        /// <param name="str">The input string .</param>
        /// <returns></returns>
        public static string RemoveCRLF(string str)
        {
            return str.Replace("\n", "").Replace("\r", "");
            //int i = 0;
            //string buf = "";
            //for (i = 0; i < str.Length; i++)
            //{
            //    if (str[i] != '\n' && str[i] != '\r')
            //    {
            //        buf += str[i];
            //    }
            //}
            //return buf;
        }

        /// <summary>
        /// Gets the date time.
        /// </summary>
        /// <param name="strDateTime">The STR date time.</param>
        /// <returns></returns>
        public static DateTime getDateTime(string strDateTime)
        {
            DateTime detReturn;
            if (DateTime.TryParse(strDateTime, out detReturn))
                return detReturn;
            else
                return DateTime.Now;
        }

        public static DateTime getDateTime(string strDateTime, string format)
        {
            DateTime detReturn;
            if (DateTime.TryParseExact(strDateTime, format, null, System.Globalization.DateTimeStyles.None, out detReturn))
                return detReturn;
            else
                return DateTime.Now;
        }

        private static object synchObj = new object();
        public static long GetOrderTicketID(Int32 userID)
        {
            lock (synchObj)
            {
                long returnValue = long.Parse(DateTime.Now.ToString("yyMMddHHmmssffff")) * 100 + userID;
                Thread.Sleep(2);
                return returnValue;
            }
        }
    }
}
